<template>
  <div>
    <h1>
      修改密码
    </h1>
    <div class="form">
      <el-form :model="formData" :rules="rules" ref="formRef">

        <el-form-item label="原密码" prop="oldPwd">
          <el-input v-model="formData.oldPwd" @blur="checkPwd"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPwd">
          <el-input type="password" v-model="formData.newPwd"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="newPwd1">
          <el-input type="password" v-model="formData.newPwd1"></el-input>
        </el-form-item>
       
        <el-form-item>
          <el-button type="primary" @click="addBtn">立即修改</el-button>
        
        </el-form-item>

      </el-form>
    </div>
  </div>
</template>

<script setup>

import {reactive,ref} from 'vue'
import {accountEditPwd,accountCheckPwd} from '@/api/account'
import { ElMessage } from 'element-plus'
import {useRouter} from 'vue-router'
const formRef = ref(null)
const router = useRouter()

const {id} = JSON.parse(sessionStorage.getItem('user'))
const formData = reactive({
  newPwd:'',
  oldPwd:'',
  newPwd1:'',
  id:id
})
const validatePassword1 = (rule,value,callback) => {
     //确认密码 是否 新密码一直 如果一致成功 不一致提示用户
     if(value !== formData.newPwd){
       callback(new Error('两次密码不一致'))
     }else{
       callback()
     }
}
const rules = {
  oldPwd:[
  {required:true,message:'请输入原密码',trigger:'blur'},
  ],
  newPwd:[
  {required:true,message:'请输入新密码',trigger:'blur'},
  ],
  newPwd1:[
  {required:true,message:'请输入确认密码',trigger:'blur'},
  { validator: validatePassword1, trigger: 'blur' }
  ]
}

const addBtn = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      accountEditPwd(formData).then(res => {
        if(res.code === 0){
          ElMessage({
            message: '修改密码成功，请重新登录',
            type: 'success',
          })

          sessionStorage.clear();
          router.push('/login') 
        }
      })
    } else {
      ElMessage({
        message: '请输入正确的信息',
        type: 'error',
      })
      return false;
    }
  });
  
}


// 判断原密码是否输入正确
const checkPwd = async() => {
    console.log(formData.oldPwd);
    let data = {
      id:formData.id,
      oldPwd:formData.oldPwd
    }
    let {code,msg} = await accountCheckPwd(data)
     if(code ==0){
      ElMessage.success(msg)
     }else{
      ElMessage.error(msg)
     }
}




</script>

<style scoped lang="scss">
.form {
  width: 500px;
  margin-top: 20px;
}
</style>